package firstServlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoad  extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("GBK");
		ServletOutputStream out1 = response.getOutputStream();
		int act = Integer.parseInt(request.getParameter("act"));
		String filename="";
		if(act==1)filename="1.rar";
		else if(act==2)filename="2.rar";
		else if(act==3)filename="3.rar";
		else filename="c.rar";
		

		File file2 = new File("d:\\"+filename);
		if (!file2.exists()) {
			response.setContentType("application/x-download");
			out1.print("file doesn't exist");
			return;
		}else {
			response.setHeader("Content-Disposition",
					"attachment; filename=default\"" + "zip"  + "\"");
			filename=filename.substring(filename.lastIndexOf("\\"));
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ filename + "\"");
		}

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file2));
			bos = new BufferedOutputStream(out1);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

}
